#include <chrono>
#include <future>
#include <iostream>
#include <thread>
#include <vector>

// 一个模拟耗时计算的函数
int heavy_computation(int base, int factor)
{
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    return base * factor;
}

int main()
{
    // 1. 使用 lambda（转发到函数）创建 packaged_task
    std::packaged_task<int(int, int)> task{heavy_computation};

    // 2. 获取 future，以等待结果或获取返回值
    std::future<int> result_future = task.get_future();

    // 3. 将任务移动到线程执行（packaged_task 不可复制，只能移动）
    std::thread worker{std::move(task), 21, 2};

    // 4. 主线程可以做别的事，这里简单输出提示
    std::cout << "Main thread is free to do other work...\n";

    // 5. 等待结果
    int result = result_future.get();
    std::cout << "Result: " << result << '\n';

    // 6. 清理线程
    worker.join();

    // ---- 扩展示例：多个任务 ----
    std::vector<std::packaged_task<int()>> tasks;
    std::vector<std::future<int>> futures;

    for (int i = 0; i < 3; ++i) {
        std::packaged_task<int()> t{[i] {
            std::this_thread::sleep_for(std::chrono::milliseconds(200));
            return i * i;
        }};
        futures.push_back(t.get_future());
        tasks.push_back(std::move(t));
    }

    std::vector<std::thread> threads;
    threads.reserve(tasks.size());

    for (auto& t : tasks) {
        threads.emplace_back(std::move(t));
    }

    for (auto& fut : futures) {
        std::cout << "Square: " << fut.get() << '\n';
    }

    for (auto& th : threads) {
        th.join();
    }

    return 0;
}